package com.mengchengnet.chaperonage.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.mengchengnet.chaperonage.BaseActivity;
import com.mengchengnet.chaperonage.R;
import com.mengchengnet.chaperonage.util.PreferenceUtil;
import com.mengchengnet.chaperonage.util.Url;
import com.mengchengnet.chaperonage.util.ViewUtil;
import com.mengchengnet.chaperonage.view.CircleImageView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

/**
 * Created by Administrator on 2017/10/26.
 * 我的资料
 */

public class MyData  extends BaseActivity implements View.OnClickListener{
    private CircleImageView headIcon;
    private TextView name;
    public String avatar;//头像
    public String userName;//姓名
    public static final int TAKE_PHOTO = 1;//拍照
    public static final int CROP_PHOTO = 2;//裁剪
    public static final int SELECT_PIC = 0;//从相册选择
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private String userId;
    private static final String TAG = "MyData";
    private HttpUtils httpUtils;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mydata);
        toolbarState=TOOLBAR_STYLE_BACK_TITLE;
        initToolbar("我的资料");
        userId=PreferenceUtil.getString(this,"userId");
        //初始化httpUtils
        httpUtils = new HttpUtils(100000);//设置他连接超时时间是100s
        httpUtils.configCurrentHttpCacheExpiry(5000);//设置缓存有效时间是5s
        headIcon= (CircleImageView) findViewById(R.id.myData_headIcon);
        headIcon.setOnClickListener(this);
        name= (TextView) findViewById(R.id.myData_name);
        name.setOnClickListener(this);
        avatar= PreferenceUtil.getString(this,"avatar");


    }

    @Override
    protected void onResume() {
        super.onResume();
        //设置头像
        if (!avatar.isEmpty()){
            ViewUtil.showImageView(this, headIcon, avatar);
        }
        userName=PreferenceUtil.getString(this,"userName");
        if (!userName.isEmpty()){
            name.setText(userName);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.myData_headIcon:
                addPopUpWindow();
                break;
            case R.id.myData_name:
                Intent intent =new Intent(MyData.this,EditNameActivity.class);
                //startActivity(intent);
                startActivityForResult(intent,0);
                break;
        }

    }




    /**
     * popupwindow弹窗
     * @param
     */
    private void addPopUpWindow(){
        View popView = LayoutInflater.from(this).inflate(R.layout.popwindow_camera,null);
        popView.setFocusable(true);
        popView.setFocusableInTouchMode(true);

        final PopupWindow window=new PopupWindow(popView, ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
        window.setFocusable(true);
        window.setOutsideTouchable(false);
        window.setAnimationStyle(R.style.anim_menu_bottombar);
        //window.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    window.dismiss();
                    return true;
                }
                return false;
            }
        });
        window.showAtLocation(popView,  Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
        View contentView=window.getContentView();
        Button btn_camera= (Button) contentView.findViewById(R.id.pop_camera);
        Button btn_cameraKu= (Button) contentView.findViewById(R.id.pop_cameraCe);
        Button btn_cancel= (Button) contentView.findViewById(R.id.pop_cancel);
        btn_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                window.dismiss();
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                // 指定照片保存路径（SD卡），temp.jpg为一个临时文件，每次拍照后这个图片都会被替换
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
                        Environment.getExternalStorageDirectory(), "temp.jpg")));
                startActivityForResult(intent, TAKE_PHOTO);

            }
        });
        btn_cameraKu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                verifyStoragePermissions(MyData.this);
                window.dismiss();
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_GET_CONTENT);//ACTION_OPEN_DOCUMENT
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("image/*");
                intent.putExtra("return-data", false);
                intent.putExtra("noFaceDetection", true); // no face detection
                intent.putExtra("crop", "true");
                //设置宽高比例
                intent.putExtra("aspectX", 1);
                intent.putExtra("aspectY", 1);
                //设置裁剪图片宽高、
                intent.putExtra("outputX", 450);
                intent.putExtra("outputY", 450);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
                        Environment.getExternalStorageDirectory(), "temp1.jpg")));
                startActivityForResult(intent,SELECT_PIC);
                //takeOrPickPhoto(false);

            }
        });
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                window.dismiss();
            }
        });


    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK)
            return;

        // 剪切处理结果
        if (requestCode == 2) {
            Bundle extras = data.getExtras();
            RequestParams params = new RequestParams();
            params.addBodyParameter("version", PreferenceUtil.getString(this,"versionCode"));
            params.addBodyParameter("loginId", userId);
            params.addBodyParameter("file", new File(Environment.getExternalStorageDirectory()
                    + "/temp.jpg"));
            upLoadImage(params, Url.uploadImage);
            if (extras != null) {
                Bitmap b= BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()
                        + "/temp.jpg");
                //photo.compress(Bitmap.CompressFormat.JPEG, 75, stream);// (0 -
                // 100)压缩文件
                headIcon.setImageBitmap(b);

            }

        }
        //图库选择文件的处理
        if (requestCode==SELECT_PIC){
            //crop(data.getData());
            if(data==null){
                return;//当data为空的时候，不做任何处理
            }
            Bitmap b= BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()
                    + "/temp1.jpg");
            headIcon.setImageBitmap(b);
            RequestParams params = new RequestParams();
            params.addBodyParameter("version", PreferenceUtil.getString(this,"versionCode"));
            params.addBodyParameter("loginId", userId);
            params.addBodyParameter("file", new File(Environment.getExternalStorageDirectory()
                    + "/temp1.jpg"));
            upLoadImage(params, Url.uploadImage);

        }

        //拍照的处理
        if(requestCode==1){
            // 设置文件保存路径这里放在跟目录下
            File picture = new File(Environment.getExternalStorageDirectory()
                    + "/temp.jpg");
            crop(Uri.fromFile(picture));
        }


        super.onActivityResult(requestCode, resultCode, data);
    }



    private void crop(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 450);
        intent.putExtra("outputY", 450);
        intent.putExtra("outputFormat", "JPEG");
        intent.putExtra("noFaceDetection", true);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
                Environment.getExternalStorageDirectory(), "temp.jpg")));
        startActivityForResult(intent, CROP_PHOTO);
    }

    public static void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE);
        }
    }

    /**
     * 图片上传
     * @param paramss
     * @param
     * @param url 服务器地址
     */
    public void upLoadImage(RequestParams paramss,  String url){

        httpUtils.send(HttpRequest.HttpMethod.POST, url, paramss, new RequestCallBack<Object>() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onLoading(long total, long current, boolean isUploading) {
                super.onLoading(total, current, isUploading);
            }

            @Override
            public void onSuccess(ResponseInfo<Object> responseInfo) {
                Log.e(TAG, "onSuccess: "+responseInfo.result.toString());
                Toast.makeText(MyData.this, "图片上传成功", Toast.LENGTH_SHORT).show();
                JSONObject obj;
                try {
                    obj=new JSONObject(responseInfo.result.toString());
                    avatar=obj.getString("big_url");

                    PreferenceUtil.putString(getApplicationContext(),"avatar",avatar);
                    if (!avatar.isEmpty()){
                        ViewUtil.showImageView(getApplicationContext(), headIcon, avatar);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {

            }

        });
    }
}
